<template>
  <el-cascader
    v-model="model"
    :options="unitList"
    :props="cascaderProps"
    :disabled="disable"
    :placeholder="placeholder"
  />
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import useUnitStore from '@/stores/unit'
import {
  CascaderNode,
  CascaderProps,
  CascaderValue,
  Resolve,
} from 'element-plus'
import { PageParam } from '@/type'
import { getUnitByLazy } from '@/api/sys/unit'

const { disable = false, placeholder = '请选择' } = defineProps<{
  disable?: boolean
  placeholder?: string
}>()

const unitStore = useUnitStore()

const model = defineModel<CascaderValue | undefined>()

const unitList = computed(() => {
  return unitStore.list.map((item) => {
    return {
      ...item,
      leaf: false,
    }
  })
})

const cascaderProps = ref<CascaderProps>({
  value: 'id',
  label: 'name',
  lazy: true,
  lazyLoad: handleLazyLoadCascader,
})

async function handleLazyLoadCascader(node: CascaderNode, resolve: Resolve) {
  const postData: PageParam = {
    currentPage: 0,
    pageSize: 0,
    sort: [],
    query: {
      node: node.data.id,
    },
  }

  const { data } = await getUnitByLazy(postData)
  if (data.status === 200 && data.data.length !== 0) {
    resolve(
      data.data.map((item: any) => {
        return {
          id: item.id,
          name: item.unitForShort,
          leaf: true,
        }
      }) || [],
    )
  } else {
    resolve([])
  }
}
</script>

<style scoped lang="scss"></style>
